package com.piece.core.web.authority.token;

import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.support.dto.UserDetailDTO;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import java.util.HashMap;
import java.util.Map;

public class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication oAuth2Authentication) {
        Map<String, Object> additionalInfo = new HashMap<>();
        Object details = oAuth2Authentication.getUserAuthentication().getDetails();
        if (null != details && details instanceof UserDetailDTO) {
            Map<String, String> parameters = oAuth2Authentication.getOAuth2Request().getRequestParameters();

            UserDetailDTO userDetail = (UserDetailDTO) details;
            additionalInfo.put("username", userDetail.getUsername());
            additionalInfo.put("deptname", userDetail.getDeptName());
            additionalInfo.put("authorities", userDetail.getAuthorities());

            String target = parameters.get("target");
            if (StringUtil.isNotEmpty(target)) {
                additionalInfo.put("target", target);
            }
        }

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}
